package com.zbkj.crmeb.merchant.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.utils.CrmebUtil;
import com.utils.DateUtil;
import com.zbkj.crmeb.export.vo.UploadUserExcelVo;
import com.zbkj.crmeb.marketing.service.StoreCouponService;
import com.zbkj.crmeb.merchant.admin.service.MerInsertUserService;
import com.zbkj.crmeb.store.model.ChannelUserUpload;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class MerInsertUserServiceImpl implements MerInsertUserService {

    @Autowired
    private UserService userService;
    @Autowired
    private StoreCouponService storeCouponService;

    /**
     * 功能描述: 批量导入用户
     * @Param: [list, merId]
     * @Return: com.zbkj.crmeb.store.model.ChannelUserUpload
     * @Author: wangzh
     * @Date: 2022/12/15 10:04
     */
    @Override
    public ChannelUserUpload importUserList(List<UploadUserExcelVo> list, Integer merId) {
        ChannelUserUpload channelUserUpload = new ChannelUserUpload();
        // 总计
        int total = list.size();
        String phones = list.stream().map(UploadUserExcelVo::getPhone).collect(Collectors.joining("|"));
        List<User> users = userService.list(Wrappers.<User>lambdaQuery()
                .eq(User::getMerId, merId)
                .apply("phone regexp '" + phones + "'"));
        // 已经存在
        int exist = users.size();
        List<String> existUserPhones = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(users)){
            existUserPhones = users.stream().map(User::getPhone).map(e -> e.split(" ")[e.split(" ").length - 1]).collect(Collectors.toList());
        }
        // 开始创建用户
        int failed = 0;
        List<User> insertUsers = new ArrayList<>();
        for (UploadUserExcelVo uploadUserExcelVo : list){
            // 用户已经存在，不生成对象
            if (existUserPhones.contains(uploadUserExcelVo.getPhone())){
                continue;
            }

            if (StringUtils.isBlank(uploadUserExcelVo.getRealName()) || StringUtils.isBlank(uploadUserExcelVo.getPhone())){
                failed ++;
                continue;
            }
            User user = new User();
            user.setRealName(uploadUserExcelVo.getRealName());
            user.setPhone(uploadUserExcelVo.getPhone());
            user.setAccount(DigestUtils.md5Hex(CrmebUtil.getUuid() + DateUtil.getNowTime()));
            user.setUserType(Constants.USER_LOGIN_TYPE_PROGRAM);
            user.setPath("/0/");
            user.setUpType(1);
            user.setLevel(1);
            user.setMerId(merId);
            insertUsers.add(user);
        }
        userService.saveBatch(insertUsers);
        for (User user : insertUsers){
            storeCouponService.bindCouponByRegisterUser(user.getUid());
        }
        String msg = "总计：" + total + ",成功：" + insertUsers.size() + ",已存在：" + exist + ",失败" + failed;
        channelUserUpload.setMsg(msg);
        channelUserUpload.setMerId(merId);
        return channelUserUpload;
    }

    /**
     * 功能描述: 单个导入
     * @Param: [realName, phone, merId]
     * @Return: java.lang.Boolean
     * @Author: wangzh
     * @Date: 2022/12/15 11:52
     */
    @Override
    public Boolean saveUser(String realName, String phone, Integer merId) {
        User one = userService.getOne(Wrappers.<User>lambdaQuery()
                .like(User::getPhone, phone)
                .eq(User::getMerId, merId)
                .last("limit 1"));
        if (Objects.nonNull(one)){
            throw new CrmebException("用户已存在");
        }
        User user = new User();
        user.setRealName(realName);
        user.setPhone(phone);
        user.setAccount(DigestUtils.md5Hex(CrmebUtil.getUuid() + DateUtil.getNowTime()));
        user.setUserType(Constants.USER_LOGIN_TYPE_PROGRAM);
        user.setPath("/0/");
        user.setUpType(1);
        user.setLevel(1);
        user.setMerId(merId);
        userService.save(user);
        storeCouponService.bindCouponByRegisterUser(user.getUid());

        return true;
    }
}
